package com.example.dessertstoressm.Service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.dessertstoressm.Mapper.InventoryMapper;
import com.example.dessertstoressm.Mapper.ItemMapper;
import com.example.dessertstoressm.Mapper.ProductMapper;
import com.example.dessertstoressm.Service.ItemService;
import com.example.dessertstoressm.domain.Inventory;
import com.example.dessertstoressm.domain.Item;
import com.example.dessertstoressm.domain.Product;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class ItemServiceImpl implements ItemService {
    @Resource
    private ItemMapper itemMapper;
    @Resource
    private ProductMapper productMapper;
    @Resource
    private InventoryMapper inventoryMapper;

    @Override
    public void updateInventoryQuantity(Map<String, Integer> param){
        String itemId = param.keySet().iterator().next();
//        System.out.println(itemId);
        Integer increment = param.get(itemId);
//        System.out.println(increment);

        increment = getInventoryQuantity(itemId) - increment;
        UpdateWrapper<Inventory> wrapper = new UpdateWrapper<>();
        wrapper.set("qty",increment)
                .eq("itemid",itemId);
        this.inventoryMapper.update(null,wrapper);
    }

    @Override
    public int getInventoryQuantity(String itemId){
        QueryWrapper<Inventory> wrapper = new QueryWrapper<>();
        wrapper.eq("itemid",itemId);
        Inventory inventory = this.inventoryMapper.selectOne(wrapper);
        return inventory.getQty();
    }

    @Override
    public List<Item> getItemListByProduct(String productId){
        QueryWrapper<Item> wrapper = new QueryWrapper<>();
        wrapper.eq("productid",productId);
        List<Item> items = this.itemMapper.selectList(wrapper);
        for (Item item : items){
            QueryWrapper<Product> wrapper1 = new QueryWrapper<>();
            wrapper1.eq("productid",productId);
            Product product = this.productMapper.selectOne(wrapper1);
            item.setProduct(product);
        }
        return items;
    }

    @Override
    public Item getItem(String itemId){
        QueryWrapper<Item> wrapper = new QueryWrapper<>();
        wrapper.eq("itemid",itemId);
        Item item = this.itemMapper.selectOne(wrapper);
        QueryWrapper<Product> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("productid",item.getProductId());
        Product product = this.productMapper.selectOne(wrapper1);
        item.setProduct(product);
        item.setQuantity(getInventoryQuantity(itemId));
        return item;
    }
}
